$NG.AllReady(function (page, { useValuesChange, useDataIndexChange, useClick,useUpdateRows, useBeforeClick, useUpdateRow }) {
    const mstform = $NG.getCmpApi("p_form_djjg_m");
    const dgrid1 = $NG.getCmpApi("p_form_djjg_d");
    const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_djjg_d");

    const storedData = localStorage.getItem("selectedUSourceData");
    console.log(storedData);

    toolbar_dgrid.insert({
        id: "user_match",
        text: "匹配物料",
        iconCls: "icon-InsertRow",
    });

    useClick(()=>{
        dgrid1.getRows().forEach(item=>{
            getItemDataByName(item)
        })
        dgrid1.refreshView()
    },"user_match")

    useBeforeClick(() => {
        console.log(`按钮编辑`,);
        const rows = dgrid1.getRows()
        const error = rows.reduce((value, item, index) => {
            if ((Number(item.u_zb_rate) || 0) == 0) {
                value.push(index + 1)
            }
            return value
        }, [])
        if (error.length != 0) {
            $NG.alert(`明细第 ${error.join("、")} 行，中标税率为0！`)
            return false
        } else {
            return true
        }
    }, 'save')
    if (storedData) {
        const parsedData = JSON.parse(storedData);
        // 获取行数
        console.log(parsedData);

        const gridCount = parsedData.length;

        let gridArr = []; // 初始化数组

        // 将 execServer 封装为 Promise
        function fetchData(item) {

            return new Promise((resolve, reject) => {
                $NG.execServer("getDjxqcByPhid", { phid: item.u_source_id, resource_table: `'${item.u_source_table}'` }, function (res) {
                    try {
                        console.log("进入功能扩展getDjxqcByPhid1");
                        if (res.count > 0) {
                            const data = JSON.parse(res.data)[0].extendObjects;
                            console.log(data);
                            let gridObj = {
                                u_source: data.djly,
                                u_material_num: data.item_phid,
                                u_material_num_EXName: data.item_no,
                                u_material_name: data.item_name,
                                // u_item_no: data.item_phid,
                                // u_item_no_EXName: data.item_no,
                                u_item_name: data.item_name,
                                u_unit: data.unit_phid,
                                u_unit_EXName: data.unit_name,
                                u_spec: data.spec,
                                u_sj_spec: data.spec,
                                u_wlfl: data.resbs_phid,
                                u_wlfl_EXName: data.resbs_name,
                                u_ncg_qty: data.u_qty,
                                u_sqyjjg: data.u_vat_prc,
                                u_pc_no: data.u_sj_no,
                                u_sj_name: data.u_sj_name,
                                u_zb_supply: data.u_zb_supply,
                                u_zb_qty: data.u_qty,
                                u_zb_prc: data.u_zb_prc,
                                u_zb_prc_vat: data.u_zb_prc_vat,
                                u_zb_rate: data.u_zb_rate,
                                u_ps_prc_vat: item.u_ps_prc_vat
                            };

                            resolve(gridObj);
                        } else {
                            console.log("功能扩展暂无数据");
                            resolve(null);
                        }
                    }

                    catch (error) {
                        console.error("功能扩展报错:", error);
                        reject(error);
                    }
                });

            });
        }

        // 执行所有异步请求
        async function fetchAllData() {
            try {
                let results = await Promise.all(parsedData.map(fetchData));
                gridArr = results.filter(Boolean); // 过滤掉 null
                // 调用新增表体行数据的函数
                if (gridArr.length > 0) {
                    dgrid1.addRows(gridArr);
                } else {
                    console.warn("未能添加任何数据");
                }
                // 清除 LocalStorage 数据
                localStorage.removeItem("selectedUSourceData");
                console.log("LocalStorage 已清除");
            } catch (error) {
                console.error("获取数据出错:", error);
            }
        }
        fetchAllData(); // 调用异步方法
    } else {
        console.log("LocalStorage 中没有数据");
    }
    ////////////////////////////////////////////////////////////--useUpdateRows--////////////////////////////////////////////////////////////
    useUpdateRows(({ args }) => {
        console.log(`表体监听`, args[0]);
        let rows = args[0]
        // 遍历数组中的每个对象
        rows.forEach((item) => {
            //默认剩余量
            let sjno = item.u_pc_no;
            console.log(sjno);
            item.u_zb_prc = (Number(item.u_zb_prc_vat) || 0) / (1 + (Number(item.u_zb_rate) || 0));
            item.u_zbwsje = (Number(item.u_zb_prc) || 0) * (Number(item.u_zb_qty) || 0);
            item.u_zbhsje = (Number(item.u_zb_prc_vat) || 0) * (Number(item.u_zb_qty) || 0);
            if (item.u_pc_no) {
                $NG.execServer("getPcBySj", { sjno: `'${sjno}'` }, function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    console.log(datas, "xxxxxxxx");
                    item.phid_pc = datas.phid_pc;
                    item.phid_pc_EXName = datas.pc_name; //单位
                    // item.u_item_sub = datas.res_bs_phid; //单位
                    // item.u_item_sub_EXName = datas.res_bs_name; //单位
                    dgrid1.refreshView();
                });
            }
        });

        dgrid1.refreshView();
    }, "p_form_djjg_d");

    // 匹配物料信息
    async function getItemDataByName(items) {
        console.log("触发方法:getItemDataByName");
        if (String(items.u_material_name || "").trim() && String(items.u_unit || "").trim() && String(items.u_spec || "").trim()) {
            $NG.execServer(
                "getItemDataByName",
                { itemname: `'${items.u_material_name?.replace(/'/g, "''")}'`, spec: `'${items.u_spec?.replace(/'/g, "''")}'`, msunit: items.u_unit },
                function (res) {
                    if (res.count > 0) {
                        let data = JSON.parse(res.data)[0].extendObjects; // 单返回值
                        items.u_material_num = data.phid;
                        items.u_material_num_EXName = data.itemno;
                        dgrid1.refreshView();
                    }
                }
            );
        }
    }
});
